package com.cwz.gateway.filter;

import com.cwz.core.utils.servle.ServletUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @program: w-demo
 * @description: 黑名单过滤器
 * @author: Wen
 **/
@Component
public class BlackListUrlFilter extends AbstractGatewayFilterFactory<BlackListUrlFilter.Config> {

	@Override
	public GatewayFilter apply(Config config) {
		return (exchange, chain) -> {
			String url = exchange.getRequest().getURI().getPath();
			if (config.matchBlacklist(url)) {
				return ServletUtils.webFluxResponseWriter(exchange.getResponse(), "请求地址不允许访问");
			}
			return chain.filter(exchange);
		};
	}

	public static class Config {
		private List<String> blacklistUrl;

		private List<Pattern> blacklistUrlPattern = new ArrayList<>();

		public boolean matchBlacklist(String url) {
			return !blacklistUrlPattern.isEmpty() && blacklistUrlPattern.stream().anyMatch(p -> p.matcher(url).find());
		}

		public List<String> getBlacklistUrl() {
			return blacklistUrl;
		}

		public void setBlacklistUrl(List<String> blacklistUrl) {
			this.blacklistUrl = blacklistUrl;
			this.blacklistUrlPattern.clear();
			this.blacklistUrl.forEach(url -> {
				// (.*?) 表示匹配任意字符到下一个符合条件的字符，(.*?) 是懒惰匹配尽可能匹配少的字符但是要匹配出所有的字符
				// 这里只是把 ** 匹配到换成 (.*?) 字符串
				this.blacklistUrlPattern.add(Pattern.compile(url.replaceAll("\\*\\*", "(.*?)"), Pattern.CASE_INSENSITIVE));
			});
		}
	}
}
